package gr.aueb.mscis.chord;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import gr.aueb.mscis.configuration.Config;
import gr.aueb.mscis.protocol.NodeIdentifier;
import gr.aueb.mscis.protocol.ProtocolType;
import gr.aueb.mscis.protocol.RemoteMessage;

public class RemoteMessageServer extends Thread{
    private static int serverPort = Config.listeningPort;
    private ObjectInputStream ois;
    ServerSocket serverSocket;
    boolean listening;
    Socket s;
    RemoteMessage clientMsg;
    NodeIdentifier predecessor;
    
    public void RemoteMessageServer(){
    	serverSocket = null;
        listening = true;
        s = null;
        clientMsg = null;
        predecessor = null;
    }	
	
	public void run(){
		try {
            serverSocket = new ServerSocket(serverPort);
            System.out.println("Tracker Started");
        

        while (listening){
        	s = serverSocket.accept();
        	
			System.out.println("Node "+s.getInetAddress() +":"+s.getPort()+" connected");
			ois = new ObjectInputStream(s.getInputStream());
			try {
				clientMsg = (RemoteMessage) ois.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("client msg: " + clientMsg.getProtocolType().toString());
			if (clientMsg.getProtocolType().equals(ProtocolType.FIND_SUCCESSOR)) {
				/*PREPEI NA SETAREI PREDESECCOR clientMsg.getNodeId();*/
				this.predecessor = clientMsg.getNodeId();
				s.close();
			}
        }
			serverSocket.close();
		} catch (IOException e) {
            System.exit(-1);
        }  		
    }
	
	public NodeIdentifier getResult(){
		return this.predecessor;
		
	}
}
